import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store'
Vue.use(VueRouter)

const routes = [{
        path: '/',
        component: () =>
            import ('../views/home/home'),
        meta: {
            title: '首页',
            keepAlive: true
        }
    },
    {
        path: '/detail/:iid/:id',
        component: () =>
            import ('../views/detail/detail'),
        meta: {
            title: '商品详情'
        }
    },

    {
        path: '/category',
        component: () =>
            import ('../views/category/category'),
        meta: {
            title: '分类',
            keepAlive: true
        }
    },
    {
        path: '/cart',
        component: () =>
            import ('../views/cart/cart'),
        meta: {
            title: '购物车' /* 需要登录 */ ,
            require: true
        }
    },
    {
        path: '/profile',
        component: () =>
            import ('../views/profile/profile'),
        meta: {
            title: '我的',
            require: true
        }
    },
    {
        path: '/register',
        component: () =>
            import ('../views/profile/register'),
        meta: {
            title: '注册'
        }
    },
    {
        path: '/login',
        component: () =>
            import ('../views/profile/login'),
        meta: {
            title: '登录'
        }
    },
    {
        path: '/order/:active?',
        component: () =>
            import ('../views/order/order'),
        meta: {
            title: '订单详情'
        }
    },
    {
        path: '/order-detail/:id?',
        component: () =>
            import ('../views/order/order-detail'),
        meta: {
            title: '订单详情',
            require: true
        }
    }
]

const router = new VueRouter({
        mode: 'history',
        base: process.env.BASE_URL,
        routes
    })
    /* 路由的前置钩子 */
router.beforeEach((to, from, next) => {
    if (to.meta.require) {
        //token
        //如果token有值的话 就可以跳转到页面上
        if (store.state.token) {
            window.document.title = to.meta.title
            next()
                /* 没有的话 就需要跳转到登录页面 */
        } else {
            router.replace('/login')
        }
    } else {
        window.document.title = to.meta.title
        next()
    }
})

export default router
